import Cookies from 'js-cookie';
import { login, logout } from '../api/ServerApi';

const user = {
    namespaced: true,
    state() {
        return {
            loginMessage: ''
        };
    },
    mutations: {
        setMessage(state, message) {
            state.loginMessage = message;
        }
    },
    actions: {
        login({ commit }, { user, vm }) {
            commit('setMessage', '');
            login(user).then(data => {
                if (data.success) {
                    Cookies.set('user', `${data.user.nickname}(${data.user.username})`);
                    Cookies.set('password', user.password);
                    Cookies.set('access', 0);
                    commit('setAvator', 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3448484253,3685836170&fm=27&gp=0.jpg', { root: true });
                    commit('setMessage', '');
                    // 登录成功跳转页面
                    vm.$router.push({ name: 'home_index' });
                } else {
                    commit('setMessage', data.message || '登录失败');
                }
            }).catch((error) => commit('setMessage', error.data.message || '登录失败'));
        },
        logout({ commit }, vm) {
            logout().then(data => {
                Cookies.remove('user');
                Cookies.remove('password');
                Cookies.remove('access');
                // 恢复默认样式
                let themeLink = document.querySelector('link[name="theme"]');
                themeLink.setAttribute('href', '');
                // 清空打开的页面等数据，但是保存主题数据
                let theme = '';
                if (localStorage.theme) {
                    theme = localStorage.theme;
                }
                localStorage.clear();
                if (theme) {
                    localStorage.theme = theme;
                }
                commit('clearOpenedSubmenu', null, { root: true });
                vm.$router.push({ name: 'login' });
            });
        }
    }
};

export default user;
